<?php

namespace App\Http\Controllers\UI;

use App\Miya\Models\Area;
use App\Miya\Models\Classify;
use App\Miya\Models\DerivativeKeyword;
use App\Miya\Models\Info;
use App\Miya\Models\Module;
use Diglactic\Breadcrumbs\Breadcrumbs;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class InfoController extends CommonController
{
    public function pc(Module $module, Classify $classify, Info $info)
    {
        $data = $this->parseInfoData($info);
        return view($info->tql, $data);
    }

    public function area(Area $area, Module $module, Classify $classify, Info $info)
    {
        $data = $this->parseInfoData($info);
        $data['area'] = $area;
        $data['title'] = sprintf('%s_%s分站', $data['title'], $area->name);
        if (request()->route()->hasParameter('derivative')) {
            $data['keywords'] = implode(',', Arr::collapse([
                $info->custom_keyword, [request()->route('derivative')]
            ]));
        } else {
            $data['keywords'] = implode(',', Arr::collapse([
                $info->custom_keyword,
                miya('keyword')->derivatives($area, $info->keyword, [1])
            ]));
        }

        return view($info->tql, $data);
    }

    public function mobile(Module $module, Classify $classify, Info $info)
    {
        $data = $this->parseInfoData($info);
        return view($info->wap_tql, $data);
    }

    /**
     * 格式化数据
     * @param $info
     * @return array
     */
    protected function parseInfoData($info)
    {
        $this->cachePageView($info);
        if (request()->route()->hasParameter('derivative')) {
            $derivative = request()->route('derivative');
            if (DerivativeKeyword::whereKeyword($derivative)->count() == 0) {
                throw new ModelNotFoundException($derivative . ' 未找到对应衍生词');
            }
        }

        $data = [];
        $data['area'] = new Area(); //地区兜底
        $info = Info::whereHas('classify')->with(Info::$DefaultRelationships)
            ->where('status', 1)->where(function ($query) {
                $query->where('is_delayed', 2)->orWhere(function ($query) {
                    $query->where('is_delayed', 1)->where('delayed_at', '<=', now());
                });
            })->findOrFail($info->id);
        $info->page_views = Cache::get('pv_' . $info->id);

        $info->avatar && $info->avatar = asset('uploads/' . $info->avatar);
        //处理多图
        if (count($info->images) > 0) {
            $info->images = array_map(function ($img) {
                return asset('uploads/' . $img);
            }, $info->images);
        } else {
            $info->avatar && $info->images = [$info->avatar];
        }

        if (request()->route()->hasParameter('derivative')) {
            $info->keywords = Arr::collapse([$info->custom_keywords, [request()->route('derivative')]]);
        } else {
            $info->keywords = $info->getKeywords();
        }

        $info->module->avatar && $info->module->avatar = asset('uploads/' . $info->module->avatar);
        $info->classify->avatar && $info->classify->avatar = asset('uploads/' . $info->classify->avatar);
        $data['info'] = $info;

        //相邻信息
        $info->next = Info::where('status', 1)->whereHas('classify')
            ->with(['module:id,name,tag', 'classify:id,name,tag'])
            ->where('module_id', $info->module_id)
            ->where(function ($query) {
                $query->where('is_delayed', 2)->orWhere(function ($query) {
                    $query->where('is_delayed', 1)->where('delayed_at', '<=', now());
                });
            })->where('id', '>', $info->id)->orderBy('id')->first();
        $info->previous = Info::where('status', 1)->whereHas('classify')
            ->with(['module:id,name,tag', 'classify:id,name,tag'])
            ->where('module_id', $info->module_id)
            ->where(function ($query) {
                $query->where('is_delayed', 2)->orWhere(function ($query) {
                    $query->where('is_delayed', 1)->where('delayed_at', '<=', now());
                });
            })->where('id', '<', $info->id)->orderBy('id', 'DESC')->first();


        $data['title'] = $info->title ?? sprintf(
                '%s_%s',
                $info->name,
                config('web.name')
            );
        $data['keywords'] = implode(',', $info->keywords);
        $data['description'] = $info->description ?? config('web.description');
        $data['module'] = request()->route('module');
        $data['classify'] = request()->route('classify');
        $data['breadcrumb'] = Breadcrumbs::render('info', [
            'module' => $info->module,
            'classify' => $info->classify,
            'info' => $info
        ]);

        return $data;
    }

    protected function cachePageView($info)
    {
        $cacheKey = sprintf('pv_%s', $info->id);

        if (Cache::has($cacheKey)) {
            Cache::increment($cacheKey);
            $cachePv = Cache::get($cacheKey);
            if ($cachePv % 10 == 0) {
                DB::table('infos')->where('id', $info->id)->update(['page_views' => $cachePv]);
            }
        } else {
            Cache::add($cacheKey, $info->page_views++, 60 * 60 * 24);
        }
    }
}
